package com.galeno.sql;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/311:59
 */
public class StreamSQLWordCount {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 12345);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        env.enableCheckpointing(100000);
        StreamTableEnvironment tbEnv = StreamTableEnvironment.create(env);
        DataStreamSource<String> lines = env.socketTextStream("galeno01", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                if (value.contains("error")) {
                    throw new RuntimeException("出现异常");
                }
                String[] split = value.split(",");
                return Tuple2.of(split[0], Integer.parseInt(split[1]));

            }
        });
        tbEnv.createTemporaryView("tb_wordCount",tpStream,$("word"),$("counts"));

      Table table=  tbEnv.sqlQuery("select word,sum(counts) totalCounts from tb_wordCount group by word");

        DataStream<Tuple2<Boolean, Row>> res = tbEnv.toRetractStream(table, Row.class);


        res.print();
        env.execute();


    }
}
